<template>
  <CloudDialog
    v-model:visible="visible"
    :loading="loading"
    title="操作确认"
    :width="480"
    :cancel="handleClose"
    :before-ok="handleSubmit">
    <template #title>
      <section class="flex-center gap-x-2">
        <i-icons-warning />
        <span class="text-1">操作确认</span>
      </section>
    </template>
    <a-spin :loading="loading" class="w-full">
      <a-form ref="formRef" layout="vertical" :model="formState" :rules="rules">
        <span class="text-[#1D2129] mb-6">
          确定<span class="text-#ED3C3C">重置</span>该用户密码吗？
        </span>
        <a-form-item label="新密码" hide-asterisk field="password">
          <a-input
            v-model.trim="formState.password"
            :max-length="64"
            placeholder="请输入密码"
            @input="
              (value: string) => (formState.password = value.replace(/\s/g, ''))
            ">
            <template #suffix>
              <span
                class="text-#11429D cursor-pointer"
                @click="handleRandomKey">
                随机
              </span>
            </template></a-input
          >
        </a-form-item>
      </a-form>
    </a-spin>
  </CloudDialog>
</template>
<script lang="ts" setup>
import { updateAdminApiUserPasswordApi } from '@/apis/modules/user'
import { type FieldRule, type FormInstance } from '@arco-design/web-vue'
interface IProps {
  record: any
}
const props = defineProps<IProps>()
const visible = defineModel<boolean>('visible', { required: true })
const formRef = ref<FormInstance>()
const formState = ref({
  password: ''
})
const rules = computed<Record<string, FieldRule[]>>(() => {
  const res: Record<string, FieldRule[]> = {
    password: [
      {
        required: true,
        validator: validatePassword
      }
    ]
  }
  return res
})
function handleRandomKey() {
  const randomString = generateRandomThreeTypesString(8, 20)
  formState.value.password = randomString
  formRef.value?.validateField(['password'])
}
const handleClose = () => {
  visible.value = false
}
const handleSubmit = async () => {
  const error = await formRef.value?.validate()
  if (error) return false
  updateAdminApiUserPasswordApi({
    id: props.record.id,
    password: formState.value.password
  }).then(() => {
    visible.value = false
    ToastUtils.success('操作成功')
  })
}
const loading = ref(false)
watch(
  () => visible.value,
  async (v) => {
    await nextTick()
    if (v) {
      handleRandomKey()
    } else {
      formRef.value?.resetFields()
    }
  }
)
</script>

<style lang="less" scoped></style>
